package utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 功能描述:
 *
 * @author liping(lpaidd50@gmail.com)
 * @version v1.0
 * @date 2016/8/8
 */
public class StringToMap {
	public static Map<String, String> toMap(String xml) throws DocumentException {
		Document document = DocumentHelper.parseText(xml);
		Element root = document.getRootElement();
		Map map = new HashMap<String, String>();
		listNodes(root, map);
		return map;
	}
	
	private static void listNodes(Element node, Map map) {
		if (!node.getName().equals("xml")) {
			map.put(node.getName(), node.getStringValue());
		}
		// 当前节点下面子节点迭代器
		Iterator<Element> it = node.elementIterator();
		// 遍历
		while (it.hasNext()) {
			// 获取某个子节点对象
			Element e = it.next();
			// 对子节点进行遍历
			listNodes(e, map);
		}
	}
	
	public static String mapToXml(Map<String, String> params) {
		Iterator<String> it = params.keySet().iterator();
		String xml = "<xml>";
		while (it.hasNext()) {
			String key = it.next();
			xml = xml + "<" + key + ">" + params.get(key) + "</" + key + ">";
		}
		xml = xml + "</xml>";
		return xml;
	}
}
